package com.wizz.trade.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wizz.trade.auth.dto.LoginDto;
import com.wizz.trade.auth.dto.SysUserChangeDto;
import com.wizz.trade.auth.dto.SysUserDto;
import com.wizz.trade.auth.dto.page.SysUserPageDto;
import com.wizz.trade.auth.entity.SysUser;
import com.wizz.trade.auth.service.LoginService;
import com.wizz.trade.auth.service.SysRoleService;
import com.wizz.trade.auth.service.SysUserService;
import com.wizz.trade.auth.vo.SysRoleVo;
import com.wizz.trade.auth.vo.SysUserVo;
import com.wizz.trade.common.LoginUser;
import com.wizz.trade.common.ResponseResult;
import com.wizz.trade.common.constant.StatusCode;
import com.wizz.trade.common.PageVo;
import com.wizz.trade.common.annotation.Public;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 权限模块/用户
 *
 * @author xialinrui
 */
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private LoginService loginService;

    @Resource
    private SysRoleService sysRoleService;


    /**
     * 用户登录
     *
     * @param user 用户
     * @return token
     */
    @Public
    @PostMapping("/login")
    public ResponseResult<Map<String, String>> login(@RequestBody LoginDto user) {
        Map<String, String> map = loginService.login(user);
        return new ResponseResult<>(StatusCode.OK, "登录成功", map);
    }


    /**
     * 用户登出
     *
     * @return 响应信息
     */
    @PostMapping("/logout")
    public ResponseResult<String> logout() {
        return new ResponseResult<>(StatusCode.OK, "登出成功");
    }


    /**
     * 添加用户
     *
     * @param sysUserDto 用户
     * @return ResponseResult
     */
    @PostMapping
    @PreAuthorize("hasAuthority('用户管理')")
    public ResponseResult<String> addsysUser(@RequestBody SysUserDto sysUserDto) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDto, sysUser);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = encoder.encode(sysUser.getPassword());
        sysUser.setPassword(password);
        sysUserService.insert(sysUser);
        List<Long> roles = sysUserDto.getRoles();
        if (!roles.isEmpty()) {
            sysUserService.bindRole(sysUser.getId(), roles);
        }
        return new ResponseResult<>(StatusCode.OK, "添加成功");
    }

    /**
     * 更新用户
     *
     * @param sysUserChangeDto 用户
     * @param id               用户id
     * @return ResponseResult
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('用户管理')")
    public ResponseResult<String> updatesysUser(@RequestBody SysUserChangeDto sysUserChangeDto, @PathVariable("id") Long id) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        SysUser sysUser = sysUserService.getOne(wrapper);
        BeanUtils.copyProperties(sysUserChangeDto, sysUser);
        sysUserService.update(sysUser);
        List<Long> roles = sysUserChangeDto.getRoles();
        if (!roles.isEmpty()) {
            sysUserService.bindRole(sysUser.getId(), roles);
        }
        return new ResponseResult<>(StatusCode.OK, "修改成功");
    }

    /**
     * 删除用户
     *
     * @param id 用户id
     * @return ResponseResult
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('用户管理')")
    public ResponseResult<String> deleteSysUser(@PathVariable("id") Long id) {
        sysUserService.delete(id);
        return new ResponseResult<>(StatusCode.OK, "删除成功");
    }

    /**
     * 查询用户信息
     *
     * @param sysUserPageDto 查询条件
     * @return 分页信息
     */
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('用户管理')")
    public ResponseResult<PageVo<SysUserVo>> getPage(SysUserPageDto sysUserPageDto) {
        PageVo<SysUser> rawPage = sysUserService.getPage(sysUserPageDto);
        List<SysUser> data = rawPage.getData();
        List<SysUserVo> dataVo = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            SysUserVo sysUserVo = new SysUserVo();
            BeanUtils.copyProperties(data.get(i), sysUserVo);
            //查询用户的角色
            sysUserVo.setRoles(sysRoleService.getRolesVoList(sysUserVo.getId()));
            for (SysRoleVo role : sysUserVo.getRoles()) {
                role.setMenus(sysRoleService.getMenusByRoleId(role.getId()));
            }
            dataVo.add(sysUserVo);
        }
        return new ResponseResult<>(StatusCode.OK, "查询成功", new PageVo<>(rawPage.getPages(), rawPage.getTotal(), dataVo));
    }

    /**
     * 禁用/启用用户
     *
     * @param id 用户id
     * @return ResponseResult
     */
    @PutMapping("/status/{id}")
    @PreAuthorize("hasAuthority('用户管理')")
    public ResponseResult<String> changeStatus(@PathVariable Long id) {
        sysUserService.changeStatus(id);
        return new ResponseResult<>(StatusCode.OK, "账号状态更改成功");
    }

    /**
     * 测试权限
     *
     * @return ResponseResult
     * @ignore
     */
    @GetMapping("/hello")
    @PreAuthorize("hasAuthority('库管高级权限')")
    public ResponseResult<String> hello() {
        return new ResponseResult<>(StatusCode.OK, "hello");
    }


    /**
     * 重置密码
     *
     * @param id 需要重置密码的用户的id
     * @return
     */
    @PostMapping("/reset/password/{id}")
    public ResponseResult<String> resetPassword(@PathVariable Integer id) {

        // TODO: 2023/7/4
        return new ResponseResult<>(StatusCode.OK, "重置密码成功");
    }


    /**
     * 获得个人信息
     *
     * @return
     */
    @GetMapping("/self/info")
    public ResponseResult<SysUserVo> getSelfUserInfo() {
        return null;
        // TODO: 2023/7/4


    }

    /**
     * 修改个人信息
     *
     * @param sysUserDto 用户信息
     * @return
     */
    @PostMapping("/modify/info")
    public ResponseResult<String> modifySelfUserInfo(SysUserDto sysUserDto) {
        // 获取目前登录的用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUser sysUser = new SysUser();
        // 实体转换
        BeanUtils.copyProperties(sysUserDto, sysUser);
        // 设置用户id便于仓储搜索
        sysUser.setId(loginUser.getUser().getId());
        // 进行更新
        sysUserService.modifySelfUserInfo(sysUser);
        return new ResponseResult<>(StatusCode.OK, "修改成功", null);

    }


}
